package com.LearnInWorld.search.service.impl;

import com.LearnInWorld.es.pojo.CourseInfo;
import com.LearnInWorld.exception.CustomException;
import com.LearnInWorld.search.dao.ESManagerMapper;
import com.LearnInWorld.search.service.ESManagerService;
import com.LearnInWorld.video.feign.CourseFeign;
import com.LearnInWorld.video.pojo.Course;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ESManagerMapper esMapper;
    @Autowired
    private CourseFeign courseFeign;

    @Override
    public void createIndexMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(CourseInfo.class);
        //创建mapper映射
        elasticsearchTemplate.putMapping(CourseInfo.class);
    }

    @Override
    public void importAll() {
        List<Course> CourseList = courseFeign.findLIst().getData();
        /*for (CourseInfo courseInfo : courseInfoList) {
            throw new RuntimeException("当前视频不存在，无法导入索引库");
        }*/
        if(CourseList==null || CourseList.size()<=0){
            throw new CustomException("当前视频不存在，无法导入索引库");
        }
        String jsonCourseInfoList = JSON.toJSONString(CourseList);
        List<com.LearnInWorld.es.pojo.CourseInfo> courseInfos = JSON.parseArray(jsonCourseInfoList, com.LearnInWorld.es.pojo.CourseInfo.class);
        esMapper.saveAll(courseInfos);
    }

    @Override
    public void importDataToEsByVideoId(String courseId) {
        Course course = courseFeign.findCourseById(courseId).getData();
        if (course==null){
            throw new CustomException("当前视频不存在，无法导入索引库");
        }
        String jsonCourseInfo = JSON.toJSONString(course);
        com.LearnInWorld.es.pojo.CourseInfo courseInfo1 = JSON.parseObject(jsonCourseInfo, com.LearnInWorld.es.pojo.CourseInfo.class);
        esMapper.save(courseInfo1);
    }
}
